/*
 * clock.c
 *
 *  Created on: 2018-3-13
 *      Author: Iron
 */
#include <time.h>
#include "sys/clock.h"
#include "sys/etimer.h"
#include "sntp.h"
#include "user_interface.h"
#include "osapi.h"

/*----------------------------------------------------------------------------*/
static volatile clock_time_t clock_ticks;
extern volatile uint32_t rtimer_clock;

static clock_time_t rtc_sec;

/*----------------------------------------------------------------------------*/
void contiki_main_clock_isr_cb(clock_time_t ticks);

/*----------------------------------------------------------------------------*/
#define CONTIKI_CLOCK_TIMER_INTERVAL  (1000 / CLOCK_CONF_SECOND) 	/* milliseconds */
LOCAL os_timer_t conitki_clock_timer;

LOCAL void ICACHE_FLASH_ATTR
conitki_clock_timer_cb(void *arg)
{
    clock_ticks++; 			// contiki system clock
    rtimer_clock += (RTIMER_ARCH_SECOND / CLOCK_CONF_SECOND);// rtimer, #define RTIMER_SECOND RTIMER_ARCH_SECOND, #define RTIMER_ARCH_SECOND      		32768

    if(clock_ticks % CLOCK_CONF_SECOND == 0){
    	rtc_sec++;
    }

	contiki_main_clock_isr_cb(clock_ticks);
}

void ICACHE_FLASH_ATTR
clock_init(void)
{
	os_timer_disarm(&conitki_clock_timer);
	os_timer_setfn(&conitki_clock_timer, (os_timer_func_t *)conitki_clock_timer_cb, (void *)0);
	os_timer_arm(&conitki_clock_timer, CONTIKI_CLOCK_TIMER_INTERVAL, 1);

	sntp_init(); // esp8266
}

/*----------------------------------------------------------------------------*/
CCIF clock_time_t ICACHE_FLASH_ATTR
clock_time(void)
{
	return clock_ticks;
}

CCIF unsigned long ICACHE_FLASH_ATTR
clock_seconds(void)
{
	os_printf("conitki get clock_seconds: %d\n", rtc_sec);
//	return time(NULL);
//	return rtimer_clock;
	return rtc_sec;
}
